package selenium;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class test3 {

	public static void main(String[] args) {
		final WebDriver driver = new ChromeDriver();
		try {
			driver.get("http://chuang.le.com/u/126516412/videolist");
			List<WebElement> aaa = driver.findElements(By.className("d_img"));
			int a =0;
			for (WebElement aaElement : aaa) {
				WebElement aeElement = aaElement.findElements(By.tagName("a")).get(0);
				String url = aeElement.getAttribute("href");
				a+=1;
				System.out.println("排序"+a+url);
				method2("D:\\1011.txt", url);
			};
			for (int i = 0; i < 125; i++) {
				driver.findElement(By.linkText("下一页")).click();
				Thread.sleep(4000);
				List<WebElement> dclass = driver.findElements(By.className("d_img"));
				for (WebElement aaElement : dclass) {
					WebElement aeElement = aaElement.findElements(By.tagName("a")).get(0);
					String url = aeElement.getAttribute("href");
					a+=1;
					System.out.println("排序"+a+":"+url);
					method2("D:\\1011.txt", url);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		driver.quit();
	}

	// 方法1：

	public void method1() {
		FileWriter fw = null;
		try {
			// 如果文件存在，则追加内容；如果文件不存在，则创建文件
			File f = new File("E:\\dd.txt");
			fw = new FileWriter(f, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(fw);
		pw.println("追加内容");
		pw.flush();
		try {
			fw.flush();
			pw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	// 方法2：

	public static void method2(String file, String conent) {
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
			out.write(conent + "\r\n");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	// 方法3：

	public static void method3(String fileName, String content) {
		try {
			// 打开一个随机访问文件流，按读写方式
			RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
			// 文件长度，字节数
			long fileLength = randomFile.length();
			// 将写文件指针移到文件尾。
			randomFile.seek(fileLength);
			randomFile.writeBytes(content + "\r\n");
			randomFile.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
